<!-- 生产管理 产品工艺路线 -->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :defaults.sync="defaults"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      :row-class-name="tableRowClassName"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.productrouteManage_add" @click="handleAdd">新 增</el-button>
        <!-- 删除 -->
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.productrouteManage_delete" @click="handleDelete">删 除 </el-button>
        <!-- 设计工艺路线 -->
        <el-button type="warning" size="small" icon="el-icon-edit" v-if="permission.productrouteManage_designRouting" @click="handleMenu({ type: 'pdesign' })"
          >设计工艺路线</el-button
        >
        <!-- 查看工艺路线 -->
        <el-button type="primary" size="small" icon="el-icon-search" v-if="permission.productrouteManage_viewRouting" @click="handleMenu({ type: 'pread' })"
          >查看工艺路线</el-button
        >
        <el-button
          type="warning"
          size="small"
          icon="el-icon-s-promotion"
          v-if="permission.productrouteManage_examine && isAudit === 'true'"
          @click="handleMenu({ type: 'toExamine' })"
          >审核</el-button
        >
        <el-button type="success" size="small" icon="el-icon-document-copy" @click="handleMenu({ type: 'copy' })">工艺复制</el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" v-if="permission.productrouteManage_edit" @click="handleOpenDetail(scope.row)">详情</el-button>
        <el-button icon="el-icon-edit" size="small" type="text" v-if="permission.productrouteManage_edit" @click.stop="handleOpenEdit(scope.row, 'edit')">编辑</el-button>
        <el-button icon="el-icon-delete" size="small" type="text" v-if="permission.productrouteManage_delete" @click.stop="$refs.crud.rowDel(scope.row, index)">删除 </el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
    </avue-crud>

    <!-- 新增/编辑 -->
    <el-dialog custom-class="productrouteManageDialog" ref="dialog" :title="dialogTitle" append-to-body :visible.sync="showDialog" top="5vh" @close="closeDialog">
      <div class="titleLeft add">
        <i class="el-icon-vertical-bar avue-group__icon"></i>
        <div class="titleName">
          <span>基础信息</span>
        </div>
      </div>
      <avue-form v-if="showDialog" ref="form" v-model="form" :option="formOption"> </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="dialogTitle === '新增'" size="small" type="primary" @click="submit"> <i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button>
        <el-button v-if="dialogTitle === '编辑'" size="small" type="primary" @click="submit"> <i class="el-icon-circle-check"></i><span>修 改</span></el-button>
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog custom-class="productrouteManageDialog" ref="dialog" title="查看" append-to-body :visible.sync="showDetailDialog" top="5vh" @close="closeDetailDialog">
      <div class="titleLeft">
        <i class="el-icon-vertical-bar avue-group__icon"></i>
        <div class="titleName">
          <span>基础信息</span>
        </div>
      </div>
      <avue-form ref="form" v-model="form" :option="formOption"> </avue-form>
      <div class="titleLeft">
        <i class="el-icon-vertical-bar avue-group__icon"></i>
        <div class="titleName">
          <span>所有版本</span>
        </div>
      </div>
      <avue-crud :option="allVersionOption" :data="allVersionData" ref="allVersionTable">
        <template slot-scope="scope" slot="menu">
          <div v-if="scope.index === 0">当前版本</div>
          <el-button v-if="scope.index != 0" icon="el-icon-view" size="small" type="text" @click="goProcess(scope.row, 'pdesign')">设计工艺</el-button>
          <el-button v-if="scope.index != 0" icon="el-icon-view" size="small" type="text" @click="goProcess(scope.row, 'pread')">查看工艺</el-button>
        </template>
      </avue-crud>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="showDetailDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>

    <!-- 工艺复制 -->
    <processReplication ref="process" v-if="processDialogVisible" :visible.sync="processDialogVisible" @copySuccess="copySuccess"></processReplication>

    <!-- 产品编码 弹框 -->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, update, remove, getProcessDetail, getProcessAllVersion, processAudit, paramDetail } from '@/api/product/productrouteManage';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { mapGetters, mapState } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import { handleJumpCache } from '@/util/util';
import processReplication from '@/views/product/components/processReplication.vue';
export default {
  components: {
    CommonModalTemplate,
    GlobalModalTemplate,
    userTableConfig,
    processReplication
  },
  mixins: [userConfig()],
  data() {
    return {
      visibile: false,
      pageCode: 'PRODUCTION_ROUTE_MANAGE',
      form: {},
      query: {},
      defaults: {},
      loading: true,
      data: [],
      commonDialog: {
        dispatch: true
      },
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 406px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        columnBtn: false,
        searchMenuSpan: 12,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        dialogClickModal: false,
        menu: true,
        menuWidth: 180,
        searchLabelWidth: 105,
        column: [
          {
            label: '产品编码',
            prop: 'productPartNo',
            search: true
          },
          {
            label: '产品名称',
            prop: 'productPartName',
            search: true
          },
          {
            label: '产品型号',
            prop: 'productPartModel'
          },
          {
            label: '工艺名称',
            prop: 'name',
            search: true
          },
          {
            label: '工艺路线编码',
            prop: 'code'
          },
          {
            label: '工艺路线版本',
            prop: 'version',
            type: 'number',
            minRows: 0,
            span: 12,
            rules: [
              {
                required: true,
                message: '请输入工艺路线版本',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '工艺路线状态',
            prop: 'status',
            type: 'select',
            span: 12,
            search: true,
            dicData: [
              {
                label: '未设计',
                value: 1
              },
              {
                label: '待审核',
                value: 2
              },
              {
                label: '已发布',
                value: 3
              }
            ],
            html: true,
            formatter: (val) => {
              if (val.status == 3) {
                return '<span style="color:#70b603">已发布</span>';
              } else if (val.status == 2) {
                return '<span style="color:blue">待审核</span>';
              } else {
                return '<span style="color:red">未设计</span>';
              }
            }
          },
          {
            label: '备注',
            prop: 'remark',
            search: true,
            overHidden: true
          },
          {
            label: '创建人',
            prop: 'createByName',
            search: true
          },
          {
            label: '创建时间',
            prop: 'createTime'
          }
        ]
      },
      form: {},
      formOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 120,
        detail: false,
        column: [
          {
            label: '产品编码',
            prop: 'productPartNo',
            type: 'search',
            disabled: true,
            order: 1,
            placeholder: '请选择 产品编码',
            rules: [
              {
                required: true,
                message: '请选择产品编码',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              if (this.dialogTitle != '查看') {
                this.openUserCommonModal({ type: 'productPartNo' });
              }
            }
          },
          {
            label: '产品名称',
            prop: 'productPartName',
            disabled: true,
            order: 2,
            placeholder: '产品名称'
          },
          {
            label: '产品型号',
            prop: 'productPartModel',
            disabled: true,
            order: 3,
            placeholder: '产品型号'
          },
          {
            label: '工艺名称',
            prop: 'name',
            order: 5,
            rules: [
              {
                required: true,
                message: '请输入 工艺名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '工艺路线编码',
            prop: 'code',
            disabled: true,
            order: 6
          },
          {
            label: '工艺路线版本',
            prop: 'version',
            span: 12,
            order: 4,
            disabled: true,
            placeholder: '工艺路线版本'
          },
          {
            label: '工艺路线状态',
            prop: 'status',
            type: 'select',
            order: 6,
            span: 12,
            search: true,
            dicData: [
              {
                label: '未设计',
                value: 1
              },
              {
                label: '待审核',
                value: 2
              },
              {
                label: '已发布',
                value: 3
              }
            ],
            html: true,
            formatter: (val) => {
              if (val.status == 3) {
                return '<span style="color:#70b603">已发布</span>';
              } else if (val.status == 2) {
                return '<span style="color:blue">待审核</span>';
              } else {
                return '<span style="color:red">未设计</span>';
              }
            },
            control: (val, form) => {
              if (this.dialogTitle === '查看') {
                return {
                  status: { display: true }
                };
              } else {
                return {
                  status: { display: false }
                };
              }
            }
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            order: 12,
            span: 24,
            maxRows: 3,
            minRows: 3,
            maxlength: 300,
            showWordLimit: true
          }
        ]
      },
      showDialog: false,
      showDetailDialog: false,
      dialogTitle: '新增',
      workSectionData: [],
      allVersionOption: {
        height: 300,
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        selection: false,
        menu: true,
        menuWidth: 180,
        refreshBtn: false,
        column: [
          {
            label: '工艺路线版本',
            prop: 'version'
          },
          {
            label: '编辑人',
            prop: 'createByName'
          },
          {
            label: '创建时间',
            prop: 'createTime'
          }
        ]
      },
      allVersionData: [],
      workSectionIdList: [],
      isAudit: false,
      importList: [],
      processDialogVisible: false
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ...mapState({
      realName: (state) => state.user.userInfo.real_name,
      userId: (state) => state.user.userInfo.user_id
    }),
    permissionList() {
      return {
        editBtn: this.vaildData(this.permission.productrouteManage_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  activated() {
    paramDetail().then((res) => {
      this.isAudit = this._get(res, 'data.data.paramValue', 'false');
      if (this.isAudit === 'true') {
        this.$refs.crud.refreshTable();
        this.allVersionOption.column = [
          {
            label: '工艺路线版本',
            prop: 'version'
          },
          {
            label: '编辑人',
            prop: 'createByName'
          },
          {
            label: '创建时间',
            prop: 'createTime'
          },
          { label: '审核人', prop: 'auditorName' },
          { label: '审核时间', prop: 'auditTime' }
        ];
      } else {
        this.$refs.crud.refreshTable();
        this.allVersionOption.column = [
          {
            label: '工艺路线版本',
            prop: 'version'
          },
          {
            label: '编辑人',
            prop: 'createByName'
          },
          {
            label: '创建时间',
            prop: 'createTime'
          }
        ];
      }
    });
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  beforeRouteEnter(to, from, next) {
    handleJumpCache(this, next, from, '/product/model-manage/orderroute-design/');
  },
  methods: {
    handleAdd() {
      this.showDialog = true;
      this.dialogTitle = '新增';
      this.formOption.detail = false;
    },
    submit() {
      console.log(this.form);
      this.$refs.form.validate(async (valid, done) => {
        if (valid) {
          this.form.processType = 'PART';
          delete this.form.version;
          update(this.form).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.showDialog = false;
              done();
            },
            (error) => {
              done();
            }
          );
        }
      });
    },
    handleOpenDetail(row) {
      this.showDetailDialog = true;
      getProcessDetail(row.id).then((res) => {
        this.form = this._get(res, 'data.data', {});
      });
      this.formOption.detail = true;
      getProcessAllVersion(row.id).then(
        (res) => {
          this.allVersionData = this._get(res, 'data.data', []);
        },
        (error) => {
          this.allVersionData = [];
        }
      );
    },
    /**
     * 打开编辑模态框
     */
    async handleOpenEdit(row, type) {
      this.showDialog = true;
      this.dialogTitle = '编辑';
      this.formOption.detail = false;
      getProcessDetail(row.id).then((res) => {
        this.form = this._get(res, 'data.data', {});
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      // let isDelete = this.selectionList.every((s) => s.status == 0 || s.status == 1);
      // if (!isDelete) {
      //   this.$message.warning('当前勾选数据中存在生产中或已完工状态，请仔细检查');
      //   return;
      // }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    // 派工 撤回 完工 设计工艺路线 查看工艺路线
    handleMenu(params) {
      let { type } = params;
      switch (type) {
        case 'pdesign':
          break;
        case 'pread':
          break;
        default:
          break;
      }
      if (this.selectionList.length === 0) {
        this.$message.warning('至少选择一条数据');
        return;
      }
      // 工艺路线 只能单条处理
      if (['pdesign', 'pread', 'copy'].includes(type) && this.selectionList.length !== 1) {
        this.$message.warning('此功能不支持批量处理，只能选择一条数据');
        return;
      }
      if (['copy'].includes(type)) {
        let { status, id } = this.selectionList[0];
        if (status != 3) {
          this.$message.warning('此工艺路线未设计/待审核状态，不可复制，请设计/审核后再进行复制，或者重新选择！');
          return;
        }
        this.processDialogVisible = true;
        setTimeout(() => {
          this.$refs.process.processId = id;
        });
        return;
      }
      if (['pdesign', 'pread'].includes(type)) {
        let { id, productPartNo, productPartId, productPartName, packingConfigId, status } = this.selectionList[0];
        this.$router.push({
          path: `/product/model-manage/orderroute-design/${type}`,
          query: {
            id,
            partNo: productPartNo,
            partMasterId: productPartId,
            partName: productPartName,
            packingConfigId,
            routeConfigured: status
          }
        });
        return;
      }
      if (['toExamine'].includes(type)) {
        for (let i = 0; i < this.selectionList.length; i++) {
          if (this.selectionList[i].isAudit) {
            this.$confirm('已审核的工艺路线不可重复审核，请取消勾选已审核信息！', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {});
            return;
          }
        }
        this.$confirm('是否确定将该产品工艺路线审核通过？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let list = [];
          this._forEach(this.selectionList, (item) => {
            list.push(item.id);
          });
          processAudit(list).then((res) => {
            this.$message.success(res.data.msg);
            this.onLoad(this.page);
          });
        });
      }
    },

    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      this.query.isLastest = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query))
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    openUserCommonModal(params) {
      let { type } = params;
      switch (type) {
        // 产品编码
        case 'productPartNo':
          this.modalName = 'productPartNoModel';
          this.$refs.commonModalTemplate.showModal();
          this.tableOption = {
            modalTitle: '选择产品信息（双击进行选择）',
            url: '/api/mes-admin/part-master/page?semifinished=true',
            isPage: true,
            rowSelectionType: 'single',
            columnDefs: [
              {
                label: '类型',
                prop: 'categoryId',
                search: true,
                type: 'tree',
                dicUrl: '/api/mes-admin/part-category/tree',
                props: {
                  label: 'title',
                  value: 'id'
                }
              },
              {
                label: '编码',
                prop: 'partNo',
                search: true
              },
              {
                label: '名称',
                prop: 'name',
                search: true
              },
              {
                label: '型号',
                prop: 'partModel'
              },
              {
                label: '描述',
                prop: 'description'
              },
              {
                label: '版本',
                prop: 'version'
              }
            ]
          };
          break;
        default:
          break;
      }
    },
    // 获取选择的物料模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'productPartNoModel':
          this.form.productPartNo = this._get(rowData, 'partNo', '');
          this.form.productPartName = this._get(rowData, 'name', '');
          this.form.productPartModel = this._get(rowData, 'partModel', '');
          this.form.productPartId = this._get(rowData, 'id', '');
          break;
        default:
          break;
      }
    },

    openPackingConfig() {
      if (this.form.partNo) {
        this.openUserCommonModal({
          type: 'packingConfig'
        });
      } else {
        this.$message({
          type: 'warning',
          message: '请先选择产品编码！'
        });
      }
    },
    goProcess(row, type) {
      this.showDetailDialog = false;
      let { id, productPartNo, productPartId, productPartName, packingConfigId, status } = row;
      this.$router.push({
        path: `/product/model-manage/orderroute-design/${type}`,
        query: {
          id,
          partNo: productPartNo,
          partMasterId: productPartId,
          partName: productPartName,
          packingConfigId,
          routeConfigured: status
        }
      });
    },
    closeDetailDialog() {
      this.form = {};
      this.allVersionData = [];
    },
    closeDialog() {
      this.$refs.form.resetFields();
      this.form = {};
    },
    tableRowClassName({ row }) {
      if (row.isHighlight === 1) {
        return 'importRow';
      }
      return '';
    },
    copySuccess() {
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    beforeOpen(done, type) {
      done();
    },
    beforeClose(done, type) {
      done();
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>
<style lang="scss" scoped>
.titleLeft {
  display: flex;
  padding: 20px 0;
  &.add {
    margin-bottom: 10px;
  }
  .titleName {
    font-size: 16px;
    font-weight: bold;
    color: rgba(0, 0, 0, 0.85);
  }
}
::v-deep .productrouteManageDialog .el-dialog__body {
  max-height: 75vh;
  overflow: auto;
  padding: 0 20px;
  .avue-form__menu {
    display: none;
  }
  .avue-crud__menu {
    display: none;
  }
}
::v-deep .importRow {
  background-color: #95f204 !important;
}
</style>
